//
//  SEWebController.m
//  SleepingElf
//
//  Created by karong on 2023/7/5.
//

#import "SEWebController.h"
#import <WebKit/WebKit.h>

@interface BaseWeakScriptMessageDelegate: NSObject <WKScriptMessageHandler>

@property (nonatomic, weak) id<WKScriptMessageHandler> scriptDelegate;

@end

@implementation BaseWeakScriptMessageDelegate

- (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate {
    self = [super init];
    if (self) {
        self.scriptDelegate = scriptDelegate;
    }
    return self;
}

- (void)userContentController:(WKUserContentController*)userContentController didReceiveScriptMessage:(WKScriptMessage*)message{
    if ([self.scriptDelegate respondsToSelector:@selector(userContentController:didReceiveScriptMessage:)]) {
        [self.scriptDelegate userContentController:userContentController didReceiveScriptMessage:message];
    }
}

@end

@interface SEWebController () <UIGestureRecognizerDelegate,WKUIDelegate,WKNavigationDelegate, WKScriptMessageHandler>
@property (weak, nonatomic) IBOutlet UIView *nav;
@property (assign, nonatomic) BOOL urlChange;
@property (strong, nonatomic) WKWebView *webView;
@property (strong, nonatomic) WKWebViewConfiguration *config;
@property (assign, nonatomic) BOOL canBack;
@property (assign, nonatomic) BOOL hiddenHud;

@end

@implementation SEWebController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    [self addWeb];
    self.title = self.titleStr;
    self.nav.hidden = !self.showNav;
}


- (void)addWeb{
    self.config = [[WKWebViewConfiguration alloc] init];
    self.config.preferences.javaScriptEnabled = YES;
    self.config.preferences.javaScriptCanOpenWindowsAutomatically = YES;
    //响应事件
    BaseWeakScriptMessageDelegate *delegate = [[BaseWeakScriptMessageDelegate alloc] initWithDelegate:self];
    WKUserContentController *controller = [[WKUserContentController alloc] init];
    [controller addScriptMessageHandler:delegate name:@"goBack"];
    [controller addScriptMessageHandler:delegate name:@"reloadWeb"];
    [controller addScriptMessageHandler:delegate name:@"finishActivity"];
    [controller addScriptMessageHandler:delegate name:@"showToast"];
    [controller addScriptMessageHandler:delegate name:@"onPaySuccess"];
    [controller addScriptMessageHandler:delegate name:@"jumpToUrl"];
    [controller addScriptMessageHandler:delegate name:@"goAddFeedback"];
    self.config.userContentController = controller;
    self.config.allowsInlineMediaPlayback = YES;
    self.webView = [[WKWebView alloc]initWithFrame:CGRectZero configuration:self.config];
    self.webView.backgroundColor = self.view.backgroundColor;
    self.webView.allowsBackForwardNavigationGestures = NO;
    self.webView.scrollView.showsVerticalScrollIndicator = NO;
    self.webView.scrollView.showsHorizontalScrollIndicator = NO;
    self.webView.UIDelegate = self;
    self.webView.navigationDelegate = self;
    [self.view addSubview:self.webView];
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).offset(self.showNav?64:0 + SEStatusBarHeight);
        make.left.right.bottom.mas_equalTo(self.view);
    }];
    NSString * string = FULL_ADDRESS([Tools fullWebUrl:self.url]);
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
    
    [self.webView loadRequest:request];
}

- (IBAction)backAction:(id)sender {
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    }
    else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    if (!self.hiddenHud) {
        self.webView.hidden = YES;
    }
    self.hiddenHud = NO;
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    ///延时0.2s 显示网页
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self showWebView];
    });
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    self.webView.hidden = NO;
}

- (void)showWebView{
    self.webView.hidden = NO;

    for (UIView* subview in self.webView.subviews) {
        for (UIGestureRecognizer* longPress in subview.gestureRecognizers) {
            if ([longPress isKindOfClass:UILongPressGestureRecognizer.class]) {
                [subview removeGestureRecognizer:longPress];
            }
        }
    }
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    NSLog(@"%@",NSStringFromSelector(_cmd));
    NSLog(@"%@",message.body);

    if ([message.name isEqualToString:@"goBack"]) {
        [self popVC];
    }else if ([message.name isEqualToString:@"reloadWeb"]) {
        self.hiddenHud = YES;
    }else if ([message.name isEqualToString:@"showToast"]){
        NSString *info = [NSString stringWithFormat:@"%@",message.body];
        [SEToast simple:info];
    }
    else if ([message.name isEqualToString:@"goAddFeedback"]){
        UIStoryboard * storyboard = [UIStoryboard storyboardWithName:@"MeController" bundle:nil];
        UIViewController * target = [storyboard instantiateViewControllerWithIdentifier:@"FeedbackController"];
        [self.navigationController pushViewController:target animated:YES];
    }
}

@end
